package com.belf.console.agent.migrate.job;

import belf.migrate.engine.admin.taskconf.SourceConf;
import com.alibaba.fastjson2.JSONObject;
import com.belf.common.core.domain.AjaxResult;
import com.belf.console.agent.migrate.BuildConnect;
import com.belf.console.agent.migrate.JobPush;
import com.belf.console.domain.DataSourceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * BuildDataSourceConf
 *
 * @author l
 * @since 2024/7/12 9:48
 */

public class BuildDataSourceConf {
    private static final Logger logger = LoggerFactory.getLogger(BuildDataSourceConf.class.getName());


    /**
     *  连接引擎获取数据
     * @param APIPath
     * @param dataSourceInfo
     * @return
     */
    public static AjaxResult  queryDataSource(String APIPath, DataSourceInfo dataSourceInfo){
        if(dataSourceInfo != null){
            SourceConf sourceConf = BuildDataSourceConf.buildSourceConf(dataSourceInfo);
            try {
                String jsonString = JSONObject.toJSONString(sourceConf);
                return JobPush.pushTask(APIPath,jsonString);
            } catch (Exception e) {
                logger.error("数据源信息 连接测试失败",e);
            }
        }
        return AjaxResult.success();
    }

    public static SourceConf buildSourceConf(DataSourceInfo sourceInfo) {
        logger.info("开始构建数据源配置");
        SourceConf sourceConf = new SourceConf();
        sourceConf.setCatalogName(sourceInfo.getType());
        sourceConf.setSchemaName(sourceInfo.getSchemaName());
        sourceConf.setDatabaseName(sourceInfo.getDatabaseName());
        sourceConf.setTaskMode(sourceInfo.getTaskMode());
        sourceConf.setTableName(sourceInfo.getTableName());
        sourceConf.setTables(sourceInfo.getTableNames());
        sourceConf.setFieldCase(sourceInfo.getFieldCase());
        if (sourceInfo.getQuote() != null) {
            sourceConf.setQuote(Boolean.parseBoolean(sourceInfo.getQuote()));
        }
        if (sourceInfo.getCaseSensitive() != null) {
            sourceConf.setCaseSensitive(Boolean.parseBoolean(sourceInfo.getCaseSensitive()));
//            sourceConf.setCaseSensitive(sourceInfo.getCaseSensitive().equals(BELF_DATA_CASE_SENSITIVE_TRUE));
        }
        sourceConf.setConnectionConf(BuildConnect.connectionConf(sourceInfo));
        sourceConf.setSql(sourceInfo.getExecuteSql());
        return sourceConf;
    }


    public static AjaxResult queryDataDbTypes(String APIPath, DataSourceInfo dataSourceInfo) {
        String catalogName = dataSourceInfo.getCatalogName();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("catalog",catalogName);
        return JobPush.pushTask(APIPath,jsonObject.toJSONString());
    }
}
